import Cookies from "js-cookie";

export const setUserCookie = (user) => {
  const defaultOptions = {
    expires: 7, // 默认7天过期
    domain: "", // 默认不设置（仅当前域名） // 允许 example.com 和 api.example.com 共享
    path: "/", // 路径范围 / 整个域名下可访问
    secure: window.location.protocol === "https:", // 根据当前协议自动设置 true(// 仅限 HTTPS) or false
  };

  Cookies.set("userId", user.userId, defaultOptions);
  Cookies.set("userName", user.userName, defaultOptions);
  Cookies.set("userAll", JSON.stringify(user), defaultOptions); // 序列化对象
};

export const removeUserCookie = () => {
  Cookies.remove("userId");
  Cookies.remove("userName");
  Cookies.remove("userAll");
};

export const getUserFromCookie = () => {
  const userAll = Cookies.get("userAll");
  return userAll ? JSON.parse(userAll) : {};
};
